package com.xmxsuperstar.app.ttac;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.xmxsuperstar.app.ttac.collections.FList;
import com.xmxsuperstar.app.ttac.thread.ImageThread;
import com.xmxsuperstar.app.ttc.client.model.TwitterStatus;

public class StatusListAdapter extends BaseAdapter {

	private final FList<TwitterStatus> statusList;
	private final Context context;
	private final Handler headImageHandler;

	public StatusListAdapter(FList<TwitterStatus> statusList, Context context,
			Handler headImageHandler) {
		this.statusList = statusList;
		this.context = context;
		this.headImageHandler = headImageHandler;
	}

	@Override
	public int getCount() {
		return statusList.size();
	}

	@Override
	public Object getItem(int position) {
		return statusList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return statusList.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater
					.inflate(R.layout.st_list_item, parent, false);
		}

		final ImageView iv = (ImageView) convertView.findViewById(R.id.img);
		iv.setTag(position);
		iv.setImageResource(R.drawable.default_head);

		URL picUrl = statusList.get(position).getUser().getProfileImageUrl();
		Thread imgThread = new ImageThread(context, headImageHandler, picUrl,
				iv);
		imgThread.start();

		TextView screenNameTv = (TextView) convertView
				.findViewById(R.id.twitter_user_screen_name);
		screenNameTv
				.setText(statusList.get(position).getUser().getScreenName());

		TextView nameTv = (TextView) convertView
				.findViewById(R.id.twitter_user_name);
		nameTv.setText(statusList.get(position).getUser().getName());

		TextView statusTv = (TextView) convertView
				.findViewById(R.id.twitter_status);
		statusTv.setText(convert(statusList.get(position).getText()));

		TextView dateTv = (TextView) convertView
				.findViewById(R.id.twitter_date);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd, HH:mm");
		dateTv.setText(df.format((statusList.get(position).getCreatedAt())));

		return convertView;
	}

	private String convert(String str) {
		String res = str;
		res = res.replaceAll("&lt;", "<");
		res = res.replaceAll("&gt;", ">");

		return res;
	}

	public FList<TwitterStatus> getstatusList() {
		return this.statusList;
	}
}
